<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会员ID" prop="memberId">
        <el-input
          v-model="queryParams.memberId"
          placeholder="请输入会员ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applicationTime">
        <el-date-picker clearable
          v-model="queryParams.applicationTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['huiyuan:applications:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['huiyuan:applications:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['huiyuan:applications:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['huiyuan:applications:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applicationsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请编号" align="center" prop="applicationNo" />
      <el-table-column label="会员名称" align="center" prop="memberName" />
      <el-table-column label="申请金额" align="center" prop="applicationAmount" />
      <el-table-column label="提现状态" align="center" prop="withdrawalStatus" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              v-if="scope.row.withdrawalStatus === '审核通过' || scope.row.withdrawalStatus === '审核拒绝'"
              link
              type="primary"
              @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
              v-else-if="scope.row.withdrawalStatus === '申请中'"
              danger
              type="primary"
              @click="handleAudit(scope.row)"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog v-model="dialogVisible" :title="dialogType === 'view' ? '查看详情' : '审核申请'" width="500px">
      <div>申请编号：{{ dialogData.applicationNo }}</div>
      <div>用户名：{{ dialogData.memberName }}</div>
      <div>申请金额：{{ dialogData.applicationAmount }}</div>
      <div>提现状态：{{ dialogData.withdrawalStatus }}</div>
      <div>申请时间：{{ dialogData.applicationTime }}</div>
      <div v-if="dialogType === 'view'">
        <div>审核时间：{{ dialogData.auditTime }}</div>
        <div>审核备注：{{ dialogData.remark }}</div>
      </div>
      <div v-else>
        <el-input v-model="auditRemark" placeholder="请输入审核备注"></el-input>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-if="dialogType === 'audit'" type="danger" @click="submitAudit('审核拒绝')">拒绝</el-button>
        <el-button v-if="dialogType === 'audit'" type="primary" @click="submitAudit('审核通过')">通过</el-button>
      </template>
    </el-dialog>



    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改提现申请记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="applicationsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请编号" prop="applicationNo">
          <el-input v-model="form.applicationNo" placeholder="请输入申请编号" />
        </el-form-item>
        <el-form-item label="会员ID" prop="memberId">
          <el-input v-model="form.memberId" placeholder="请输入会员ID" />
        </el-form-item>
        <el-form-item label="申请金额" prop="applicationAmount">
          <el-input v-model="form.applicationAmount" placeholder="请输入申请金额" />
        </el-form-item>
        <el-form-item label="提现状态" prop="withdrawalStatus">
          <el-select v-model="form.withdrawalStatus" placeholder="请选择提现状态">
            <el-option label="申请中" value="申请中" />
            <el-option label="审核通过" value="审核通过" />
            <el-option label="审核拒绝" value="审核拒绝" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="applicationTime">
          <el-date-picker clearable
            v-model="form.applicationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择申请时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核时间" prop="auditTime">
          <el-date-picker clearable
            v-model="form.auditTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择审核时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input v-model="form.auditRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Applications">
import { listApplications, getApplications, delApplications, addApplications, updateApplications } from "@/api/huiyuan/applications"
import {addFlow,getBalanceAfter} from "@/api/huiyuan/flow";

const { proxy } = getCurrentInstance()

const applicationsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dialogVisible = ref(false)
const dialogType = ref('view') // 'view' or 'audit'
const dialogData = ref({})
const auditRemark = ref('')

function handleView(row) {
  dialogType.value = 'view'
  dialogData.value = { ...row }
  dialogVisible.value = true
}
function handleAudit(row) {
  dialogType.value = 'audit'
  dialogData.value = { ...row }
  auditRemark.value = ''
  dialogVisible.value = true
}
async function submitAudit(result) {
  // 这里请替换为你的实际审核接口
  await updateApplications({
    id: dialogData.value.id,
    withdrawalStatus: result,
    remark: auditRemark.value
  })
  dialogVisible.value = false
  getList() // 刷新表格
  if(result == '审核通过'){
    try {
      console.log(form.value.memberId)
      // 获取上一条记录的balanceAfter
      const response = await getBalanceAfter(form.value.memberId)
      console.log("获取上一条记录响应：", response)
      let lastARecord = 0
      if (response.data && response.data !== null) {
        lastARecord = Number(response.data)
      }
      console.log("计算得到的lastARecord：", lastARecord)
      // 生成新的flowId
      const flowId = generateFlowId()
      // 构建资金流水数据
      const flowData = {
        flowId: flowId,
        memberId: form.value.memberId,
        changeType: '余额提现',
        changeAmount: form.value.applicationAmount,
        balanceAfter: lastARecord-Number(form.value.applicationAmount),
        flowTime: form.value.auditTime,
        description: `会员余额提现，提现单号为：${form.value.applicationNo}`
      }
      // 添加资金流水记录
      console.log("准备添加资金流水记录，数据：", flowData)
      await addFlow(flowData)
      console.log("资金流水记录新增成功")
      proxy.$modal.msgSuccess("资金流水记录新增成功")
    } catch (error) {
      console.error("资金流水记录新增失败：", error)
      proxy.$modal.msgError("资金流水记录新增失败：" + error.message)
    }

  }
}

/** 生成流水ID */
function generateFlowId() {
  // 从本地存储取最新序号，无则初始化为 0
  let latestNo = parseInt(localStorage.getItem('flowIdNo') || '0')
  // 生成新 flowId：tx_ + 6 位补零序号
  const flowId = `tx_${String(latestNo).padStart(6, '0')}`
  // 序号 +1 存回，下次用
  localStorage.setItem('flowIdNo', latestNo + 1)
  return flowId
}


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    memberId: null,
    withdrawalStatus: null,
    applicationTime: null,
  },
  rules: {
    applicationNo: [
      { required: true, message: "申请编号不能为空", trigger: "blur" }
    ],
    memberId: [
      { required: true, message: "会员ID不能为空", trigger: "blur" }
    ],
    applicationAmount: [
      { required: true, message: "申请金额不能为空", trigger: "blur" }
    ],
    withdrawalStatus: [
      { required: true, message: "提现状态不能为空", trigger: "change" }
    ],
    applicationTime: [
      { required: true, message: "申请时间不能为空", trigger: "blur" }
    ]
  }
})
const { queryParams, form, rules } = toRefs(data)

/** 查询提现申请记录列表 */
function getList() {
  loading.value = true
  listApplications(queryParams.value).then(response => {
    applicationsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    applicationNo: null,
    memberId: null,
    applicationAmount: null,
    withdrawalStatus: null,
    applicationTime: null,
    auditTime: null,
    auditRemark: null
  }
  proxy.resetForm("applicationsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加提现申请记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getApplications(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改提现申请记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["applicationsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateApplications(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addApplications(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除提现申请记录编号为"' + _ids + '"的数据项？').then(function() {
    return delApplications(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('huiyuan/applications/export', {
    ...queryParams.value
  }, `applications_${new Date().getTime()}.xlsx`)
}

getList()
</script>
